<?php

/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace Consumer;

use \Exception;

/**
 * 冰柜处理
 * @author 
 */
class Refrigerator extends Controller {

	private $door_key;//门状态KEY REDIS
	private $is_open_door;//门是否已经开开
	private $user_id;//当前用user_id
	
    /**
     * 开门
     * @param array $data
     * @return void
     */
    public function openDoor($data) {
        try {
            if (empty($data['door_id'])) {
                throw new Exception('开门ID不能为空');
            }
            if (empty($data['user_id'])) {
                throw new Exception('用户ID不能为空');
            }
			$redis = $this->getRedisModule();
			//门状态
			$door_key = DOOR_STATUS.$data['door_id'];
			//用户和门的关系
			$user_door_key = USER_DOOR_STATUS.$data['user_id'];
			if($status = $redis->get($door_key)){
				//判断门是否已经开开
				$msg = ($status>=DOOR_OPENING)?'门已开':'开门中';
				$user_door = $redis->get($user_door_key);
				if(empty($user_door)){
					$msg = '别人正在开门中,请你稍后再试';
				}else{
					$msg = '';
				}
				throw new Exception($msg);
			}
			$redis->multi();
			//门状态
			$redis->set($door_key,QQ_DOOR_OPEN);
			//线上用户列表
			$redis->rpush(ON_LINE_USER_ID_LIST,$data['user_id']);
			//用户状态
			$redis->set(USER_STATUS.$data['user_id'],QQ_DOOR_OPEN);
			//用户和门的关系
			$redis->set($user_door_key,$data['door_id']);
			//门对应的用户ID
			$redis->set(USER_DOOR_RE.$data['door_id'],$data['user_id']);
			//支付方式
			$redis->set(USER_PAY_TYPE.$data['user_id'],$data['pay_type']);
			$redis->exec();
			return $this->returnJson('请求成功', 200);
        } catch (Exception $e) {
            return $this->returnJson($e->getMessage(), 300);
        }
    }
	
	
	//收集门信息  硬件方 一秒钟 调用一次
	public function collectInfo($data){
		try{
			$this->addData($data);
			$door_id = $data['door_id'];//门ID
			if (empty($door_id)) {
                throw new Exception('门ID不能为空');
            }
			$redis = $this->getRedisModule();
			//门状态
			$door_key = DOOR_STATUS.$door_id;
			$this->door_key = $door_key;
			//输出开门请求
			if(($status = $redis->get($door_key)) && $status==QQ_DOOR_OPEN){
				//设置 成开门中
				$this->setOpening($door_id);
				return $this->jsonEncode(['response'=>'openDoor']);
			}elseif($this->is_open_door){
				$this->setOpened($door_id);
				return $this->returnJson('门已经开开', 200);
			}else{
				return $this->jsonEncode(['response'=>'none']);
			}
		}catch (Exception $e) {
            return $this->returnJson($e->getMessage(), 300);
        }
	}
	
	
	//生成订单 1、关门 2、生成订单  $data = ['door_id'=>1,'items'=>[['sku_id'=>2,'num'=>1]]]
	public function completeOrder($data){
		try{
			//关门
			$this->closeDoor($data);
			//添加订单
			$this->addOrder($data);
			return $this->returnJson('结算成功', 200);
		}catch (Exception $e) {
			$msg = json_encode($data);
			$this->addLog('completeOrder',$msg.$e->getMessage(),'error');
            return $this->returnJson($e->getMessage(), 300);
        }
	}
	
	
	//关门
	private function closeDoor($data){
		if (empty($data['door_id'])) {
            throw new Exception('门ID不能为空');
        }
		$door_id = $data['door_id'];
		$door_key = DOOR_STATUS.$door_id;
		$redis = $this->getRedisModule();
		if(($status=$redis->get($door_key)) && $status!=DOOR_OPENED){
			throw new Exception('门未开不能关门');
		}
		$key = USER_DOOR_RE.$door_id;
		$user_id = $redis->get($key);
		if(empty($user_id)){
			throw new Exception('用户ID不能为空');
		}
		$this->user_id = $user_id;
		if(!empty($data['items'])){
			return true;
		}
		//是否有购买商品
		$status = DOOR_CLOSED_NO;
		$redis->multi();
		$redis->set($door_key,$status);
		//用户状态
		$key = USER_STATUS.$user_id;
		$redis->set($key,$status);
		//线上用户列表
		$redis->rpush(ON_LINE_USER_ID_LIST,$user_id);
		$redis->exec();
		return true;
	}
	
	
	//生成订单
	private function addOrder($data){
		//没有拿商品直接返回成功
		if(empty($data['items'])){
			return true;
		}
		$redis = $this->getRedisModule();
		$pay_type = $redis->get(USER_PAY_TYPE.$this->user_id);//支付方式
		//添加订单url
		$url = ADD_ORDER_URL;
		//获取生成订单的URL
		$data = $this->curlPost($url,['id'=>$data['door_id'],'member_id'=>$this->user_id,'payType'=>$pay_type,'items'=>$data['items']]);
		if(empty($data)){
			throw new Exception('生成订单失败'.$url.var_export($data,true));
		}
		//添加日志
		$this->addLog('addOrder',$data);
		$data = json_decode($data,true);
		if($data['code']!=200){
			throw new Exception($data['msg']);
		}
		//user_id:order_pay:order_sn:money
		$redis->rpush(USER_ORDER_OPT_LIST,$this->user_id.':'.$pay_type.':'.$data['data']['order_sn'].':'.$data['data']['money']);
		return true;
	}
	
	
	//设置 成开门中
	private function setOpening($door_id){
		if(empty($door_id)){
			throw new Exception('门编号不能为空');
		}
		$redis = $this->getRedisModule();
		$key = USER_DOOR_RE.$door_id;
		$user_id = $redis->get($key);
		if(empty($user_id)){
			throw new Exception('用户ID不能为空');
		}
		$redis->multi();
		$redis->set($this->door_key,DOOR_OPENING);
		//用户状态
		$key = USER_STATUS.$user_id;
		$redis->set($key,DOOR_OPENING);
		//线上用户列表
		$redis->rpush(ON_LINE_USER_ID_LIST,$user_id);
		$redis->exec();
		return true;
	}
	
	//设置 门状态  为   门已开
	private function setOpened($door_id){
		if(empty($door_id)){
			throw new Exception('门编号不能为空');
		}
		$redis = $this->getRedisModule();
		//门已开
		$key = USER_DOOR_RE.$door_id;
		$user_id = $redis->get($key);
		if(empty($user_id)){
			throw new Exception('用户ID不能为空');
		}
		$status = $redis->get($this->door_key);
		if($status>=DOOR_OPENED){
			throw new Exception('门已经开开了');
		}
		$redis->multi();
		$redis->set($this->door_key,DOOR_OPENED);
		//用户状态
		$key = USER_STATUS.$user_id;
		$redis->set($key,DOOR_OPENED);
		//线上用户列表
		$redis->rpush(ON_LINE_USER_ID_LIST,$user_id);
		$redis->exec();
	}
	
	
	//添加福柜信息
	private function addData($data){	
		$this->is_open_door = (isset($data['is_open']) && $data['is_open']==1) ? 1:0;//是否门已经开
	}
	
	
	
	//刷新所有
	public function flushall(){
		$redis = $this->getRedisModule();
		$redis->flushall();
		return '同步成功';
	}

	//获取redisModule
    private function getRedisModule() {
        return Tool::getRedisModule();
    }

}
